package com.lzq.course.server.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lzq.course.server.domain.RoleResource;
import com.lzq.course.server.domain.RoleResourceExample;
import com.lzq.course.server.dto.RoleResourceDto;
import com.lzq.course.server.dto.PageDto;
import com.lzq.course.server.mapper.RoleResourceMapper;
import com.lzq.course.server.util.CopyUtil;
import com.lzq.course.server.util.UuidUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class RoleResourceService {

    @Resource
    private RoleResourceMapper roleResourceMapper;

    /**
     * example 这个文件很有用
     * 可以帮我们生成where order 查询
     * 不用单独写sql的增删改查
     */
    public void list(PageDto<RoleResourceDto> pageDto) {
        // 分页查询 页码不是从0开始
        PageHelper.startPage(pageDto.getPage(), pageDto.getSize());

        // 排序
        RoleResourceExample roleResourceExample = new RoleResourceExample();

        // 查询
        List<RoleResource> roleResourceList = roleResourceMapper.selectByExample(roleResourceExample);

        PageInfo<RoleResource> pageInfo = new PageInfo<>(roleResourceList);
        pageDto.setTotal(pageInfo.getTotal());

        List<RoleResourceDto> roleResourceDtoList = CopyUtil.copyList(roleResourceList, RoleResourceDto.class);

        pageDto.setList(roleResourceDtoList);
    }

    /**
     * 保存 修改
     * @param roleResourceDto
     */
    public void save(RoleResourceDto roleResourceDto) {
        //BeanUtils.copyProperties(roleResourceDto, roleResource);
        RoleResource copyRoleResource = CopyUtil.copy(roleResourceDto, RoleResource.class);

        if (StringUtils.isEmpty(roleResourceDto.getId())) {
            // 新增
            // 八位的 id
            copyRoleResource.setId(UuidUtil.getShortUuid());

            Date now = new Date();

            roleResourceMapper.insert(copyRoleResource);
        } else {
            // 编辑
            roleResourceMapper.updateByPrimaryKey(copyRoleResource);
        }
    }

    /**
     * 删除
     * @param id
     */
    public void delete(String id) {
        roleResourceMapper.deleteByPrimaryKey(id);
    }
}
